import java.util.concurrent.CountDownLatch;

/**
 * @author JeanHu
 * @date 2025/11/4
 * @description
 */


public class test {
    public static void main(String[] args) throws InterruptedException {
        int n = 100; // 线程数量 = 打印数量
        CountDownLatch[] latches = new CountDownLatch[n];

        // 初始化每个线程的 latch
        for (int i = 0; i < n; i++) {
            latches[i] = new CountDownLatch(1);
        }

        for (int i = 0; i < n; i++) {
            int index = i;
            new Thread(() -> {
                try {
                    // 等待前一个线程
                    if (index > 0) {
                        latches[index - 1].await();
                    }
                    System.out.println("线程" + (index + 1) + " 打印：" + (index + 1));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 当前线程执行完，放行下一个线程
                    latches[index].countDown();
                }
            }).start();
        }
    }
}

